#!/bin/bash
#author:xieziqiang

KA_VERSION="2.3.1"
KA_SRC_PATH="/usr/local/src"
COMPILE_ARG="--prefix=/usr/local"

color() {
    local message="$1"
    local status="$2"
    local terminal_width
    terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "${message}"  "${middle_column}"
    # Print the status message
    printf "["
    case ${status} in
        success|0)
            echo -en  "${SETCOLOR_SUCCESS}  OK  "
            ;;
        failure|1)
            echo -en  "${SETCOLOR_FAILURE}FAILED"
            ;;
        *)
            echo -en "${SETCOLOR_WARNING}WARNING"
            ;;
    esac
    echo -e "${SETCOLOR_NORMAL}]"
}

check_user () {
    if [ "$(id -u)" = "0" ];then
        color "当前执行脚本用户为管理员用户" 0
    else
        color "当前执行脚本用户为非管理员用户" 1
        exit
    fi
}

check_file () {
    if  [ -e "keepalived-${KA_VERSION}.tar.gz" ];then
        color "当前路径发现keepalived-${KA_VERSION}.tar.gz" 0
    else
        color "当前路径未发现keepalived-${KA_VERSION}.tar.gz" 1
        exit
    fi
}

compile_install_keepalived () {
    apt update \
    && apt install -y make gcc libssl-dev libnl-3-dev libnl-genl-3-dev pkg-config \
    && color "依赖安装成功" 0 \
    || { color "安装依赖失败" 1;exit; }

    if ! [ -d /etc/keepalived ];then
        mkdir -pv /etc/keepalived
    fi

    tar -xvf "keepalived-${KA_VERSION}.tar.gz" -C "${KA_SRC_PATH}"
    cd  "${KA_SRC_PATH}/keepalived-${KA_VERSION}"  || { color "没有对应的文件夹！" 1;exit; }
    ./configure "${COMPILE_ARG}"
    make && make install
    \cp ./keepalived/keepalived.service /etc/systemd/system/
    \cp -b ./keepalived/etc/keepalived/keepalived.conf.sample /etc/keepalived/keepalived.conf
    systemctl daemon-reload
    systemctl enable  keepalived.service \
    && systemctl start keepalived.service \
    && color "keepalived服务启动成功" 0 \
    || { color "keepalived服务启动失败" 1;exit; }
}

main () {
    check_user
    check_file
    compile_install_keepalived
}

main